<?php
namespace app\common\service\cabinet;

use app\common\enums\RefundStatusEnum;
use app\common\enums\RefundTypeEnum;
use app\common\library\cabinet\Cabinet;
use app\common\enums\OrderStatusEnum;
use app\common\enums\PayStatusEnum;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use app\common\library\wechat\WxPay;

/**
 * Class OrderService
 * @package app\common\service\cabinet
 * @author luoxianhui
 */
class OrderService
{
    public $noticeService;

    public function __construct()
    {
        $this->noticeService = new NoticeService();
    }

    /**
     * 付款成功处理
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function paySuccess($orderId){
        $order = Db::table('evt_customer_cabinet_order')->where('id', $orderId)->find();
        if ($order['pay_status'] == PayStatusEnum::PAY_STATUS_SUCCESS) {
            return true;
        }

        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update([
            'order_status' => OrderStatusEnum::ACCOMPLISH,
            'pay_status' => PayStatusEnum::PAY_STATUS_SUCCESS,
            'pay_time' => time(),
        ]);
        Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->update([
            'order_status' => OrderStatusEnum::ACCOMPLISH
        ]);

        $cabinets = new Cabinet();
        $orderProduct = Db::table('evt_customer_cabinet_order_product')->field('product_id,container_id')->where('order_id', $orderId)->select()->toArray();
        foreach ($orderProduct as $k => $v){
            $sale = Db::table('evt_customer_cabinet_goods')->where('id', $v['product_id'])->value('sale');
            $sale +=1; //添加销量
            Db::table('evt_customer_cabinet_goods')->where('id', $v['product_id'])->update(['is_repair' => 2, 'sale' => $sale]);
            //实物開門
            $channel_id = Db::table('evt_customer_cabinet_container')->where('id', $v['container_id'])->value('channel_id');
            $cabinets->openDoor($order['devid'], $channel_id);
        }
        //消息推送
        $this->noticeService->orderPaySuccessNotice($orderId);
    }


    /**
     * 取消订单
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function cancelOrder($orderId){
        $order = Db::table('evt_customer_cabinet_order')->field('order_status')->where('id', $orderId)->find();
        if (!self::isCancel($order['order_status'])) {
            return false;
        }
        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update(['order_status' => OrderStatusEnum::REPEAL]);
        Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->update(['order_status' => OrderStatusEnum::REPEAL]);
        return true;
    }


    /**
     * 申请售后
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function applyAfterSales($orderId){
        $order = Db::table('evt_customer_cabinet_order')->where('id', $orderId)->find();
        if (!self::isSales($order['order_status'], $order['admin_id'], $orderId)) {
            return false;
        }
        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update(['order_status' => OrderStatusEnum::RETUREN_ING]);
        Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->update(['order_status' => OrderStatusEnum::RETUREN_ING]);
        //给商家发送售后申请通知
        $this->noticeService->afterSalesNotice($orderId);
        return true;
    }


    /**
     * 取消申请售后
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function cancelAfterSales($orderId){
        $order = Db::table('evt_customer_cabinet_order')->where('id', $orderId)->find();
        if (!self::isCancelSales($order['order_status'])) {
            return false;
        }
        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update(['order_status' => OrderStatusEnum::ACCOMPLISH]);
        Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->update([
             'order_status' => OrderStatusEnum::ACCOMPLISH,
             'refund_status' => RefundStatusEnum::CANCEL,
            ]);
        //给商家发送 取消售后申请通知
        $this->noticeService->cancelAfterSalesNotice($orderId);
        return true;
    }


    /**
     * 删除订单
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delOrder($orderId){
        $order = Db::table('evt_customer_cabinet_order')->where('id', $orderId)->find();
        if (!self::isDel($order['order_status'])) {
            return false;
        }
        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update(['status' => 2]);
        return true;
    }


    /**
     * 超时订单处理
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function overtimeOrderHandle(){
        $orderList =  $order = Db::table('evt_customer_cabinet_order')->where('order_status', OrderStatusEnum::NOT_PAY)->select();
        if (count($orderList) > 0) {
            $time = time();
            foreach ($orderList as $order) {
                $auto_cancel = Db::table('evt_mini_user')->where('id', $order['admin_id'])->value('auto_cancel');
                $auto_cancel = ($auto_cancel > 0)?  ($time - $auto_cancel*60): $time;
                if ($order['create_time'] <= $auto_cancel) {
                    Db::table('evt_customer_cabinet_order')->where('id', $order['id'])->update(['order_status' => OrderStatusEnum::REPEAL]);
                    Db::table('evt_customer_cabinet_order_product')->where('order_id', $order['id'])->update(['order_status' => OrderStatusEnum::REPEAL]);
                    $this->noticeService->overtimeNotice($order['id']);
                }
            }
        }
    }

    /**
     * 确认（同意）退款
     * @param $orderId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function confirmRefund($orderId){
        $order = Db::table('evt_customer_cabinet_order')->where('order_status', OrderStatusEnum::RETUREN_ING)->where('id', $orderId)->find();
        if (!$order) {
            return false;
        }
        $productList = Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->select()->toArray();
        $count = count($productList);
        $refundPrice = 0;
        foreach ($productList as $k => $product) {
            if ($product['order_status'] == OrderStatusEnum::RETUREN_ING) {
                $refundProductPrice = $product['price']*$product['num'] - $product['point_money'] - $product['coupon_money'] - $product['level_money'];


                $refundPrice += $refundProductPrice;
                Db::table('evt_customer_cabinet_order_product')->where('id', $product['id'])->update([
                   'order_status' => OrderStatusEnum::RETUREN,
                   'refund_type' => RefundTypeEnum::MONEY,
                   'refund_status' => RefundStatusEnum::CONSENT,
                   'refund_require_money' => $refundProductPrice,
                   'refund_time' => time(),
                ]);
            }
        }

        $refund_balance_money = 0;
        if ($order['payment_type'] == 2) { //余额支付
            $refund_balance_money = $refundPrice;
        }

        $refundNum = Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->where('order_status', OrderStatusEnum::RETUREN_ING)->count();
        if ($count > $refundNum) { //部分商品退款完毕
            Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update([
                //'order_status' => OrderStatusEnum::ACCOMPLISH,
                'order_status' => OrderStatusEnum::RETUREN,
                'refund_money' => $order['refund_money'] + $refundPrice,
                'refund_balance_money' => $order['refund_balance_money'] + $refund_balance_money,
            ]);
        } else { //商品全部退款完毕
            $refundPriceTotal = $order['refund_money'] + $refundPrice;
            if ($refundPriceTotal != $order['pay_money']) { //确保退款不超出支付金额
                $refundPrice = $order['pay_money'] - $order['refund_money'];
            }

            Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update([
                'order_status' => OrderStatusEnum::RETUREN,
                'refund_money' => $order['refund_money'] + $refundPrice,
                'refund_balance_money' => $order['refund_balance_money'] + $refund_balance_money,
            ]);
        }

        $user = Db::table('evt_mini_member_list')->where('id', $order['user_id'])->find();

        if ($order['payment_type'] == 1) {
            $room = Db::table('evt_mini_room_list')->where('id', $order['store_id'])->find();
            $wxapp = Db::table('evt_mini_match')->where('wxapp_id', $room['admin_id'])->find();
            $wxConfig = array(
                'app_id' => $wxapp['app_id'],
                'app_key' => $wxapp['key'],
                'mchid' => $wxapp['wc_hid'],
                'app_secret' => $wxapp['api_key'],
                'apikey' => $wxapp['api_key'],
                'apiclient_url' => $wxapp['apiclient_url'],
                'apiclient_key_url' => $wxapp['apiclient_key_url']
            );
            $WxPay = new WxPay($wxConfig);
            if (!$WxPay->refund($order['out_trade_no'], $order['pay_money'], $refundPrice)) {
                return false;
            }
        } else {
            $userBa['balance'] = $user['balance'] + $refundPrice;
            if (Db::table('evt_mini_member_list')->where('id', $order['user_id'])->update($userBa)) {// 记录余额变动
                $userbalance = array(
                    'admin_id' => $user['admin_id'],
                    'price' => $refundPrice,
                    'type' => 1,
                    'status' => $order['order_sn'],
                    'before_price' => $user['balance'],
                    'aater_price' => $userBa['balance'],
                    'create_time' => time(),
                    'user_id' => $user['id'],
                    'content' => "商品柜退款",
                );
                Db::table('evt_mini_admin_user_balance')->insert($userbalance);
            }

        }
        $this->noticeService->refundSuccessNotice($orderId, $refundPrice);
        return true;

    }

     /**
     * 确认拒接退款
     * @param $orderId
     * @throws DbException
     */
    public function  confirmRefuse($orderId){
        Db::table('evt_customer_cabinet_order')->where('id', $orderId)->update([
            'order_status' => OrderStatusEnum::ACCOMPLISH,
        ]);

        Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)->update([
            'order_status' => OrderStatusEnum::ACCOMPLISH,
            'refund_status' => RefundStatusEnum::NO_PASS_ALWAYS,
        ]);
        
        $this->noticeService->refundRefuseNotice($orderId);
    }

    /**
     * 是否可取消订单
     * @param $orderStatus
     * @return bool  true 是 false 否
     */
    public static function isCancel($orderStatus){
       return ($orderStatus == OrderStatusEnum::NOT_PAY)? true: false;
    }
    /**
     * 是否可立即支付
     * @param $orderStatus
     * @return bool  true 是 false 否
     */
    public static function isPay($orderStatus){
        return ($orderStatus == OrderStatusEnum::NOT_PAY)? true: false;
    }
    /**
     * 是否可申请售后
     * @param $orderStatus
     * @return bool  true 是 false 否
     */
    public static function isSales($orderStatus, $adminId, $orderId){
        $info = Db::table('evt_customer_cabinet_order_product')->where('order_id', $orderId)
            ->where('refund_status', '<', 0)
            ->find();
        if (!empty($info)) {
            return false;
        }
        $unsubscribe = Db::table('evt_mini_admin_make')->where('admin_id', $adminId)->value('is_goods_gui_unsubscribe');
        return ($orderStatus == OrderStatusEnum::ACCOMPLISH && $unsubscribe)? true: false;
    }
    /**
     * 是否可取消申请售后
     * @param $orderStatus
     * @return bool true 是 false 否
     */
    public static function isCancelSales($orderStatus){
        return  ($orderStatus == OrderStatusEnum::RETUREN_ING) ? true: false;
    }
    /**
     * 是否可删除订单
     * @param $orderStatus
     * @return bool  true 是 false 否
     */
    public static function isDel($orderStatus){
        return ($orderStatus == OrderStatusEnum::RETUREN || $orderStatus == OrderStatusEnum::ACCOMPLISH) ? true: false;
    }


}